package logic

import (
	"context"
	"errors"
	"goods-manager/goodrpc/goodrpc"
	"goods-manager/goodrpc/internal/svc"
	"goods-manager/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodAddLogic) GoodAdd(in *goodrpc.GoodAddRequest) (*goodrpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line
	var good model.Good
	model.DB.Debug().Where("goodName=?", in.GoodName).Find(&good)
	if good.ID != 0 {
		return nil, errors.New("商品已存在,请更换")
	}
	if good.GoodName == "" {
		return nil, errors.New("商品名称不存在,请添加")
	}
	goods := model.Good{
		GoodName:  in.GoodName,
		GoodPrice: float64(in.GoodPrice),
		GoodStock: int(in.GoodStock),
		GoodStyle: in.GoodStyle,
	}
	err := model.DB.Debug().Create(&goods).Error
	if err != nil {
		return nil, err
	}

	return &goodrpc.GoodAddResponse{
		GoodID: int64(goods.ID),
	}, nil
}
